import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:lib_music/lib_music.dart';
import 'package:lib_music/lib_mic.dart';
import '../base/MyGestureDetector.dart';
import 'MicPage.dart';
import 'MusicDataSendUtil.dart';
import 'PlayListDialog.dart';

class CtrlBarWidget extends StatelessWidget {
  const CtrlBarWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        _BtnWidget(
          child: Icon(Icons.mic_outlined),
          onTap: () {
            LibMusic.instance.stopPlay();
            Navigator.of(context).push(
              CupertinoPageRoute(
                builder: (BuildContext context) {
                  return const MicPage();
                },
              ),
            );
          },
        ),
        _BtnWidget(child: Icon(Icons.skip_previous_outlined), onTap: () => LibMusic.instance.prePlay()),
        ListenableBuilder(listenable: MusicDataSendUtil.instance, builder:  (BuildContext context, Widget? child) {
          return _BtnWidget(
            child: LibMusic.instance.isPlayingMusic ? Icon(Icons.pause_outlined) : Icon(Icons.play_arrow_outlined),
            onTap: () async {
              var musicManager = LibMusic.instance;
              if (musicManager.isPlayingMusic) {
                LibMusic.instance.pausePlay();
              } else {
                if (musicManager.currentProgress > 0) {
                  LibMusic.instance.continuePlay();
                } else {
                  var bean = musicManager.getCurrentMusic();
                  if (bean == null) {
                    var list = await musicManager.getMusicList();
                    if (list.isNotEmpty) {
                      bean = list[0];
                    }
                  }
                  if (bean != null) {
                    LibMusic.instance.startPlay(bean);
                  }
                }
              }
            },
          );
        }),
        _BtnWidget(child: Icon(Icons.skip_next_outlined), onTap: () => LibMusic.instance.nextPlay()),
        _BtnWidget(
          child: Icon(Icons.format_list_bulleted_outlined),
          onTap: () async {
            var bean = await PlayListDialog.show(context);
            if (bean != null) {
              LibMusic.instance.stopPlay();
              Future.delayed(const Duration(milliseconds: 400), () async {
                LibMusic.instance.startPlay(bean);
              });
            }
          },
        ),
      ],
    );
  }
}

class _BtnWidget extends StatelessWidget {
  final Widget child;
  final GestureTapCallback? onTap;

  const _BtnWidget({super.key, required this.child, this.onTap});

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: MyGestureDetector(
        onTap: onTap,
        child: Center(child: child),
      ),
    );
  }
}
